/**
 * 
 */
package cn.nawang.ebeim.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.nawang.ebeim.api.domain.Ca;
import cn.nawang.ebeim.api.domain.Customer;
import cn.nawang.ebeim.api.domain.Department;
import cn.nawang.ebeim.api.domain.User;
import cn.nawang.ebeim.api.repository.CaRepository;
import cn.nawang.ebeim.api.repository.UserRepository;
import cn.nawang.ebeim.api.repository.impl.CaQueryRepositoryImpl;
import cn.nawang.ebeim.api.repository.impl.CustomerQueryImpl;
import cn.nawang.ebeim.api.repository.impl.DepartmentQueryImpl;
import cn.nawang.ebeim.api.repository.impl.UserQueryImpl;
import cn.nawang.ebeim.api.service.UserService;
import cn.nawang.ebeim.api.utils.Constant;
import cn.nawang.ebeim.api.utils.DateOperate;
import cn.nawang.ebeim.api.utils.Util;
import cn.nawang.ebeim.api.vo.UserView;

@Service("userService")
public class UserServiceImpl implements UserService {

  @Autowired
  UserRepository userRepository;
  @Autowired
  private UserQueryImpl userQueryImpl;
  @Autowired
  private CustomerQueryImpl customerQueryImpl;
  @Autowired
  private DepartmentQueryImpl departmentQueryImpl;
  @Autowired
  private CaQueryRepositoryImpl caQueryRepositoryImpl;
  @Autowired
  private CaRepository caRepository;

  public User findOne(String id) {
    User user = null;
    try {
      user = userRepository.findOne(id);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return user;
  }

  @Override
  public User findUserByMobile(String mobile) {
    return userQueryImpl.findUserByMobile(mobile);
  }

  @Override
  public User findUserByMobileNotId(String mobile, String id) {
    return userQueryImpl.findUserByMobileNotId(mobile, id);
  }

  @Override
  public User findUserByEmail(String email) {
    return userQueryImpl.findUserByEmail(email);
  }

  @Override
  public User findUserByEmailNotId(String email, String id) {
    return userQueryImpl.findUserByEmailNotId(email, id);
  }

  @Override
  public User findUserByUsername(String username) {
    return userQueryImpl.findUserByUsername(username);
  }

  @Override
  public User findUserByUsernameNotId(String username, String id) {
    return userQueryImpl.findUserByUsernameNotId(username, id);
  }

  @Override
  public User findUserByUsernameOrMobileOrEmail(String username, String mobile, String email) {
    return userQueryImpl.findUserByUsernameOrMobileOrEmail(username, mobile, email);
  }

  @Override
  public User findUserByUsernameOrMobileOrEmailNotId(String username, String mobile, String email,
      String id) {
    return userQueryImpl.findUserByUsernameOrMobileOrEmailNotId(username, mobile, email, id);
  }

  @Override
  public UserView findUserById(String userId) {
    return userQueryImpl.findUserById(userId);
  }

  @Override
  public boolean update(User user) {
    try {
      userRepository.save(user);
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }

  @Override
  public boolean save(User user) {
    try {
      Date d = new Date();
      user.setCreateTime(DateOperate.formatDateToString(d, DateOperate.DATE_TIME_STYLE_All));
      user.setIsUpdateDefaultPwd(Constant.NO);
      user.setId(String.valueOf(userQueryImpl.findMaxRecordId()));
      user.setPassword(Util.hash(user.getPassword()));
      user.setRole(Constant.ROLE_USER);

      user.setIsFirstLogin(Constant.USER_IS_FIRST_LOGIN_YES);
      user.setSafeLevel(Constant.USER_SAFE_LEVEL_ZERO);
      user.setSpaceCapacity(Constant.USER_SAFE_LEVEL_ZERO);
      List<Ca> cas=caQueryRepositoryImpl.findByParam("labId", user.getLabId());
      Ca ca=cas.get(0);
      user.setLabType(ca.getLabType());
      userRepository.save(user);
      ca.setIsBind(Constant.IS_BIND_ONE);
      caRepository.save(ca);
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }

  @Override
  public Map<String, Object> intoUpdateUser(String userId) {
    Map<String, Object> resultMap = new HashMap<String, Object>();
    if (Util.isBlank(userId)) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "参数有误。");
      return resultMap;
    }
    UserView uv = userQueryImpl.findUserById(userId);
    if (uv == null) {
      resultMap.put("code", Constant.CODE_ERROR);
      resultMap.put("desc", "很抱歉，没找到用户资料信息。");
      return resultMap;
    }
    resultMap.put("code", Constant.CODE_SUCCESS);
    resultMap.put("desc", "数据查询成功。");
    resultMap.put("userObj", uv);

    // 状态MAP
    List<Map> statusList = new ArrayList<Map>();
    Map<String, Object> statusMap = new HashMap<String, Object>();
    for (Map.Entry<String, String> item : Constant.USER_STATUS_TYPE.entrySet()) {
      statusMap.put("id", item.getKey());
      statusMap.put("name", item.getValue());
      statusList.add(statusMap);
    }
    resultMap.put("statusList", statusList);

    // 客户列表MAP
    Map<String, Object> customerMap = new HashMap<String, Object>();
    Customer customer = customerQueryImpl.findCustomerById(uv.getCustomerId());
    if (customer != null) {
      customerMap.put("id", customer.getId());
      customerMap.put("name", customer.getName());
      customerMap.put("spaceSize", customer.getSpace());
      resultMap.put("companyObj", customerMap);
    } else {
      resultMap.put("companyObj", null);
    }

    // 部门列表MAP
    Department dept = departmentQueryImpl.findDeptById(uv.getDepartId());
    if (dept != null) {
      // 取出客户下的所有部门
      List<Department> list = departmentQueryImpl.findDeptByCustomerId(uv.getCustomerId());
      // 通过递归得到用户选中的所有关联部门编号路径
      String recursiveGetDeptId = getSelectList(new StringBuffer(), dept, list);
      if (recursiveGetDeptId != null && !"".equals(recursiveGetDeptId)) {
        // 得到部门路径
        String[] deptIdStr = recursiveGetDeptId.split(",");
        // 使用map来存放用户选中的所有关联部门id
        Map<String, String> selDeptIdMap = new HashMap<String, String>();
        for (int i = 0; i < deptIdStr.length; i++) {
          selDeptIdMap.put(deptIdStr[i], deptIdStr[i]);
        }
        customerMap.put("deptList", getDeptMap(list, selDeptIdMap));
      }
    } else {
      customerMap.put("deptList", null);
    }
    return resultMap;
  }

  /**
   * @author 许炜毅
   * @Description 生成部门关联下拉框列表数据
   * @param list 客户下的所有部门列表
   * @param selDeptIdMap 用户选中的部门编号
   * @return List<Map>
   * @date 2015年8月11日下午2:47:19
   *
   * @修改人
   * @修改日期
   */
  public List<Map> getDeptMap(List<Department> list, Map<String, String> selDeptIdMap) {
    List<Map> resultList = new ArrayList<Map>();
    int countLevel = 0;// 累计当前子部门是第几级下拉框
    for (Department obj : list) {
      // 从部门的根节点开始
      if (obj.getParentId() == 0) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", obj.getId());
        map.put("name", obj.getName());
        // 处理当前部门是否有子部门
        proCurrNodeIsChildNode(selDeptIdMap, countLevel, list, obj, map);
        resultList.add(map);
      }
    }
    return resultList;
  }

  /**
   * 根据当前部门得到子部门数据
   */
  public void proCurrNodeIsChildNode(Map<String, String> selDeptIdMap, int countLevel,
      List<Department> list, Department obj, Map<String, Object> map) {
    // 说明有子部门
    if (selDeptIdMap.containsKey(String.valueOf(obj.getId()))) {
      countLevel += 1;
      List<Map> childDeptList = new ArrayList<Map>();
      for (Department childObj : list) {
        if (childObj.getParentId() == obj.getId().intValue()) {
          Map<String, Object> childDeptMap = new HashMap<String, Object>();
          childDeptMap.put("id", childObj.getId());
          childDeptMap.put("name", childObj.getName());
          // 判断是否有子部门，有的话再进行回调
          if (selDeptIdMap.containsKey(String.valueOf(childObj.getId()))) {
            proCurrNodeIsChildNode(selDeptIdMap, countLevel, list, childObj, childDeptMap);
          }
          childDeptList.add(childDeptMap);
        }
      }
      // 说明有子部门，并且子部门下拉列表未超出用户已选择的最后一个部门列表
      if (childDeptList != null && childDeptList.size() > 0) {
        if (countLevel < selDeptIdMap.size()) {
          map.put("childrenList", childDeptList);
        }
      }
    }
  }

  /**
   * 根据dept对象得到上N级部门完整编号路径，直到顶级部门结束 如：3,2,1； 说明:部门编号3的上一级部门编号为2， 部门编号2的上一级部门编号为1；依此类推；
   */
  private String getSelectList(StringBuffer sb, Department dept, List<Department> all) {
    sb.append(dept.getId() + ",");
    sb.append(assmce(dept, all));
    return sb.toString();
  }

  public String assmce(Department dept, List<Department> all) {
    List<Department> childmenus = null;
    childmenus = getChildrenDept(dept.getParentId().intValue(), all);
    if (childmenus == null || childmenus.size() < 1) return "";
    StringBuffer sb = null;
    sb = new StringBuffer("");
    for (Department obj : childmenus) {
      this.getSelectList(sb, obj, all);
    }
    return sb.toString();
  }

  private List<Department> getChildrenDept(int fid, List<Department> all) {
    List<Department> result = new ArrayList<Department>();
    for (Department m : all) {
      if (m.getId() == fid) {
        result.add(m);
      }
    }
    return result;
  }

  @Override
  public Map<String, Object> findUserByUsernameAndPwd(String username, String password,
      HttpServletRequest request) {
    Map<String, Object> userMap = new HashMap<String, Object>();
    User user = userQueryImpl.findUserByUsername(username);
    userMap.put("code", Constant.CODE_ERROR);
    // 如果用户是否为空
    if (user == null) {
      userMap.put("message", "用户不存在");
      return userMap;
    } else if (!user.getPassword().equalsIgnoreCase(Util.hash(password))) {// 验证密码是否相等
      userMap.put("message", "密码不正确");
      return userMap;
    } else if (user.getStatus().equals(Constant.USER_STATUS_TYPE_ONE)) {// 验证用户是否停用
      userMap.put("message", "该用户已停用，请联系管理员");
      return userMap;
    } else {
      userMap.put("code", Constant.CODE_SUCCESS);
      userMap.put("message", "用户登录成功");
      userMap.put("user", user);
      // 验证用户是否有新增客户权限
      if (user.getUsername() == "admin") {
        userMap.put("authority", "有新增客户的权限");
      } else {
        userMap.put("authority", "无新增客户的权限");
      }
    }
    return userMap;
  }

  @Override
  public User findByCustomerIdAndAdmin(String customerId) {
    return userQueryImpl.findByCustomerIdAndAdmin(customerId);
  }

  @Override
  public Map<String, Object> findUserAvailableSpace(String customerId) {
    User adminUser=this.findByCustomerIdAndAdmin(customerId);
    Map<String,Object> map=new HashMap<String,Object>();
    map.put("code", Constant.CODE_ERROR);
    Double availableSpaceSize=Double.valueOf(adminUser.getSpaceSize())-Double.valueOf(adminUser.getSpaceCapacity());
    map.put("spaceSize", adminUser.getSpaceSize());
    map.put("availableSpaceSize", availableSpaceSize);
    map.put("code", Constant.CODE_SUCCESS);
    return map;
  }

  @Override
  public void addSpaceSize(String id, String addSpaceSize) {
    User user=userQueryImpl.findUserByUserid(id);
    User adminUser=userQueryImpl.findByCustomerIdAndAdmin(user.getCustomerId());
    // 用户追加空间
    double userSpaceSize=Double.valueOf(user.getSpaceSize())+Double.valueOf(addSpaceSize);
    String userSpaceSizeStr=String.valueOf(userSpaceSize);
    user.setSpaceSize(userSpaceSizeStr.substring(0,userSpaceSizeStr.indexOf(".")));
    
    // 管理员记录追加了的空间大小
    double usedSpaceSize=Double.valueOf(adminUser.getSpaceCapacity())+Double.valueOf(addSpaceSize);
    String usedSpaceSizeStr=String.valueOf(usedSpaceSize);
    adminUser.setSpaceCapacity(usedSpaceSizeStr.substring(0, usedSpaceSizeStr.indexOf(".")));
    userRepository.save(user);
    userRepository.save(adminUser);
    
  }
}
